import Request from "luch-request"
import {commons} from "@/utils/commons"
import type {HttpRequestConfig} from "luch-request"

export default class CustomRequestInstance {
    instance: Request
    // 自定义配置
    extra: CustomRequest.ExtraConfig

    constructor(
        config: HttpRequestConfig,
        extra: CustomRequest.ExtraConfig = {
            showError: true,
            showLoading: true
        }) {
        this.instance = new Request(config)
        this.extra = extra

        this.setInterceptors()
    }

    // 设置拦截器
    setInterceptors() {
        // 请求拦截
        this.instance.interceptors.request.use((config: any) => { // 可使用async await 做异步操作
            // loading
            this.showLoading()
            // 初始化请求拦截器时，会执行此方法，此时data为undefined，赋予默认{}
            config.data = config.data || {}
            let token = uni.getStorageSync("token")
            if (token) {
                config.header["OPEN-API-TOKEN"] = "Bearer " + token
            }
            return config
        }, error => {
            return Promise.resolve(error)
        })

        // 响应拦截器
        this.instance.interceptors.response.use((response) => {
            // loading
            this.hideLoading()
            let data = response.data
            if (data.code !== 200) {
                //未登录时清空缓存跳转
                if (data.code == 401) {
                    uni.clearStorageSync()
                    commons.showModelConfirm('您还未登录！请先登录 ', () => {
                        uni.switchTab({
                            url: "/pages/tab-bar/mine"
                        })
                    }, () => {
                        uni.navigateBack()
                    })
                    return Promise.reject(data)
                } else {
                    if (this.extra.showError) {
                        commons.showToast(data?.message)
                    }

                    return Promise.reject(data)
                }
            }
            return data || {}
        }, (error) => {
            // loading
            this.hideLoading()
            if (this.extra.showError) {
                commons.showToast(error?.data?.msg)
            }
            return Promise.resolve(error)
        })
    }

    showLoading() {
        if (this.extra.showLoading) {
            commons.showLoading()
        }
    }

    hideLoading() {
        if (this.extra.showLoading) {
            commons.hideLoading()
        }
    }
}
